package com.rent.core.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

/**
 * @Author zhang
 * @create 2022/4/15 10:33
 */
@Slf4j
@EnableCaching
@Configuration
public class CaffeineCacheConfig {

    //配置CacheManager
    @Primary
    @Bean(name = "Caffeine")
    public CacheManager Caffeine() {
        log.info("加载缓存数据");
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        // 设置缓存方式
        cacheManager.setCaffeine(Caffeine.newBuilder()
                //cache的初始容量值
                .initialCapacity(100)
                //maximumSize用来控制cache的最大缓存数量，maximumSize和maximumWeight(最大权重)不可以同时使用，
                .maximumSize(1000)
                //最后一次写入或者访问后过久过期
                .expireAfterAccess(500, TimeUnit.SECONDS)
                //创建或更新之后多久刷新,需要设置cacheLoader
                .refreshAfterWrite(10, TimeUnit.SECONDS));
        cacheManager.setCacheLoader(cacheLoader());
        cacheManager.setAllowNullValues(false);//是否允许值为空
        return cacheManager;
    }

    /**
     * 必须要指定这个bean，refreshAfterWrite配置属性才生效
     */
    @Bean
    public CacheLoader<Object, Object> cacheLoader() {
        return new CacheLoader<Object, Object>() {
            @Nullable
            @Override
            public Object load(@NonNull Object o) {
                return null;
            }

            @Override
            public Object reload(@NonNull Object key, @NonNull Object oldValue) {
                return oldValue;
            }
        };
    }
}
